<template>
    <div class="account-index-page page-container"
         ref="pageContainer">
        <div class="table-container">
            <div class="table-header">
                <div class="i-flex i-flex-ai-c">
                    <div class="table-title i-flex-auto">
                        账号管理
                    </div>
                    <div class="i-flex-none">
                        <el-button type="text" @click="handleEdit"><i class="el-icon-plus"></i> 新建</el-button>
                    </div>
                </div>
            </div>
            <div class="model-box margin shadow-box radius">
                <template v-if="accounts.length">
                    <div class="table-content" ref="tableContent">
                        <el-table row-key="id"
                                  ref="table"
                                  :data="accounts"
                                  :height="tableContentHeight"
                                  style="width: 100%">
                            <el-table-column prop="id"
                                             label="编号"
                                             align="center"
                                             width="55"/>
                            <el-table-column align="center"
                                             label="类型"
                                             min-width="100">
                                <div slot-scope="scope">
                                    {{ typeList[scope.row.type] }}
                                </div>
                            </el-table-column>
                            <el-table-column prop="name"
                                             label="名称"
                                             min-width="240"/>
                            <el-table-column prop="key"
                                             label="密匙"
                                             min-width="180"/>
                            <el-table-column prop="created_at"
                                             label="创建日期"
                                             width="180"/>
                            <el-table-column align="center"
                                             label="启用"
                                             min-width="100">
                                <div slot-scope="scope">
                                    <el-switch v-model="scope.row.enable">
                                    </el-switch>
                                </div>
                            </el-table-column>
                            <el-table-column min-width="150"
                                             label="操作"
                                             align="right">
                                <template slot-scope="scope">
                                    <el-button size="mini"
                                               @click="handleEdit(scope.row, 'edit')">
                                        修改
                                    </el-button>
                                    <el-button size="mini"
                                               type="danger"
                                               :loading="scope.row.deleteModelLoading"
                                               @click="handleDeleteButton(scope.row,scope.$index)">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <div class="table-pagination">
                        <el-pagination background
                                       @current-change="handleCurrentChange"
                                       layout="total, sizes, prev, pager, next"
                                       @size-change="handleSizeChange"
                                       :page-sizes="[10, 25, 50, 100]"
                                       :page-size="pageSize"
                                       :total="meta.total || 0">
                        </el-pagination>
                    </div>
                </template>
                <div v-else>
                    么有数据
                </div>
            </div>
            <el-dialog v-if="showDialog"
                       :title="dialogType === 'new' ? '创建新账户' : '修改账户'"
                       :visible.sync="dialogStatus">
                <el-form :model="form"
                         :rules="rules"
                         v-loading="submitLoading"
                         ref="form">
                    <el-form-item label="类型" prop="type" :label-width="formLabelWidth">
                        <el-select v-model="form.type" placeholder="Select">
                            <el-option
                                    v-for="(item,key) in typeList"
                                    :key="key"
                                    :label="item"
                                    :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="名称" prop="name" :label-width="formLabelWidth">
                        <el-input v-model="form.name" placeholder="请输入名称"/>
                    </el-form-item>
                    <el-form-item label="密匙(key)" prop="key" :label-width="formLabelWidth">
                        <el-input v-model="form.key" placeholder="请输入密匙"/>
                    </el-form-item>
                    <el-form-item label="令牌(token)" prop="token" :label-width="formLabelWidth">
                        <el-input v-model="form.token" placeholder="请输入令牌"/>
                    </el-form-item>
                    <div class="dialog-footer">
                        <el-button @click="dialogStatus = false">
                            取 消
                        </el-button>
                        <el-button @click="handleValidatorForm"
                                   type="primary">
                            确 定
                        </el-button>
                    </div>
                </el-form>

            </el-dialog>
        </div>
    </div>
</template>

<script>
    import { mapState, mapActions } from 'vuex';
    import { responseNotify }       from "../../assets/simple";
    import tableContent             from '../../mixins/tableContentHeight';
    import loading                  from '../../mixins/loading';
    import pagination               from '../../mixins/pagination';

    const defaultForm = {
        key  : '',
        token: '',
        name : '',
        type : 'zx',
    };

    export default {
        name    : 'account',
        mixins  : [ tableContent, loading, pagination ],
        data() {
            return {
                form             : defaultForm,
                typeList         : {
                    'zx': '整形',
                    'kq': '口腔'
                },
                dialogType       : 'new',
                search           : '',
                dialogFormVisible: false,
                showDialog       : false,
                formLabelWidth   : '120px',
                rules            : {
                    name : [
                        { required: true, message: '请输入名称', trigger: 'blur' },
                    ],
                    key  : [
                        { required: true, message: '请输入密匙', trigger: 'blur' },
                    ],
                    token: [
                        { required: true, message: '请输入令牌', trigger: 'blur' },
                    ],
                },
                submitLoading    : false,
                showSaveButton   : false,
                saveButtonLoading: false,
            }
        },
        computed: {
            ...mapState({
                accounts(state) {
                    return state.Account.accounts;
                },
                meta(state) {
                    return state.Account.accountMeta;
                },
            }),
            dialogStatus: {
                get() {
                    return this.dialogFormVisible;
                },
                set(val) {
                    this.showDialog = val;

                    if (val) {
                        this.$nextTick(() => {
                            this.dialogFormVisible = val;
                        })
                    }
                    else {
                        setTimeout(() => {
                            this.dialogFormVisible = val;
                        }, 250);
                    }
                }
            },
        },
        mounted() {
            this.handleInit();
        },
        methods : {
            ...mapActions({
                getAccount: 'Account/accounts',
                createData: 'Account/createData',
                updateData: 'Account/updateData',
                deleteData: 'Account/deleteData',
            }),
            async handleDeleteButton(item, index) {

                try {
                    await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText : '取消',
                        type             : 'warning'
                    });
                    this.handleDelete(item);
                } catch (e) {
                    console.log('e :', e);
                }
            },
            async handleInit(text = '加载账户数据...') {
                this.showLoading({
                    text,
                });
                await this.handleGetData();
                this.closeLoading();
            },
            async handleGetData() {
                let res = await this.getAccount({
                    page_size: this.pageSize,
                    page     : this.currentPage
                });
            },
            handleEdit(item = {}, type = 'new') {
                this.dialogType   = type;
                this.form         = Object.assign({}, defaultForm, item);
                this.dialogStatus = true;
            },
            async handleDelete(item) {
                if (!item.deleteModelLoading) {
                    this.$set(item, 'deleteModelLoading', true);
                    await this.handleDeleteData(item.id);
                    this.$set(item, 'deleteModelLoading', false);
                }
            },
            async handleDeleteData(id) {
                let res = await this.deleteData(id);
                responseNotify(res);
                await this.handleGetData();
            },
            async handleSaveOrder() {
                this.saveButtonLoading = true;
                let res                = await this.saveOrder();
                this.saveButtonLoading = false;
                this.showSaveButton    = false;
                responseNotify(res);
                await this.handleGetData();
            },
            handleValidatorForm() {
                if (this.submitLoading) {
                    return;
                }
                let form = this.$refs.form;
                form.validate(async (valid) => {
                    if (valid) {
                        this.submitLoading = true;

                        this.dialogType === 'new' ? await this.handleCreate() : await this.handleUpdate();
                        this.submitLoading = false;
                        this.dialogStatus  = false;
                        this.handleInit('重新加载数据');
                    }
                })
            },
            async handleCreate() {
                let res = await this.createData(this.form);
                responseNotify(res);
            },
            async handleUpdate(data) {
                data = data || this.form;

                if (!data || !data.id) {
                    app.$notify.error({
                        title   : '错误',
                        message : '发现未知错误 : ID 不存在.',
                        duration: 1000
                    });
                    return;
                }

                let res = await this.updateData(data);
                responseNotify(res);

            },
            async handleSwitch(item, display) {
                if (item.switchLoading) {
                    return;
                }

                item.switchLoading = true;
                await this.handleUpdate({
                    id: item.id,
                    display
                });
                item.switchLoading = false;
                await this.handleGetData();

            }
        }
    }
</script>
